<?php
namespace app\api\controller;
require_once EXTEND_PATH . 'qrcode/vendor/autoload.php';
use app\common\controller\Api;
use Endroid\QrCode\Writer\PngWriter;
use think\Cache;
use think\Config;
use think\Controller;
use think\Db;
use think\Log;


use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;

use think\Request;

/**
 * 微信操作类
 */
class Wx extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $APPID = 'wx5049d19335c00bd7';
    protected $APPSECRET = '3984d5bde23df705ed0535b52dca93d3';
    protected $TOKENCACHENAME = '3984d5bde23df705ed0535b52dca93d3';
//
//    public function _initialize()
//    {

       // parent::_initialize();

//        if (!Config::get('fastadmin.usercenter')) {
//            $this->error(__('User center already closed'));
//        }
//        $this->brand=model('admin/Brand');
//        $this->homestatistics=model('admin/kuozhan/Homestatistics');
//        $this->friend=model('admin/kuozhan/Friend');
//        $this->studaying=model('admin/kuozhan/Studaying');
//        $this->article=model('admin/kuozhan/Articles');
//        $this->area=model('admin/Area');
//        $this->jihua=model('admin/kuozhan/Jihua');

    //}
//    protected $APPID = '';
//    protected $APPSECRET = '';
//    protected $TOKENCACHENAME = '';
//    public function _initialize()
//    {
//        $this->APPID = config('wxpay.APPID');
//        $this->APPSECRET = config('wxpay.APPSECRET');
//    }
//        protected $noNeedLogin = ['*'];
//        protected $noNeedRight = ['*'];


        public function _initialize()
    {
        parent::_initialize();


        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
                $this->APPID = 'wx5049d19335c00bd7';//config('wxpay.APPID');
                $this->APPSECRET = '3984d5bde23df705ed0535b52dca93d3';//config('wxpay.APPSECRET');
//        $this->brand=model('admin/Brand');
//        $this->homestatistics=model('admin/kuozhan/Homestatistics');
//        $this->friend=model('admin/kuozhan/Friend');
//        $this->studaying=model('admin/kuozhan/Studaying');
//        $this->article=model('admin/kuozhan/Articles');
//        $this->area=model('admin/Area');
//        $this->jihua=model('admin/kuozhan/Jihua');

    }


    public function curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

public function index(){
            echo 11;
}
    /**
     * @return string
     *得到普通的accesstoken
     */
    public function getGeneralAccessToken()
    {

        $this->APPID ='wx5049d19335c00bd7';// config('wxpay.APPID');

        $this->APPSECRET = '3984d5bde23df705ed0535b52dca93d3';//config('wxpay.APPSECRET');

        $this->TOKENCACHENAME = '3984d5bde23df705ed0535b52dca93d3';

//echo 1;
        return Cache::remember($this->TOKENCACHENAME, function () {
//echo 2;
//exit;
            try {
                $get_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->APPID . '&secret=' . $this->APPSECRET;

                $data = $this->curl($get_token_url);
//dump($data);
                $json_obj = json_decode($data, true);
//dump($json_obj);
//exit;
                if ($this->TOKENCACHENAME == 'accessToken') {
                    return $json_obj["access_token"];
                } else {
                    return [
                        'accessToken' => $json_obj["access_token"],
                        'expirationTime' => time() + 3600,
                    ];

                }

            } catch (\Exception $e) {
                // 记录报错 或 抛出异常
            }

        }, 3600);
    }

    /**
     * @param $url
     * @param $json
     * @return mixed
     * 使用curl方法发送json数据
     */
    public function postData($url, $json)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    /**
     * @param $access_token
     * @param $action_name
     * @param $scene_id
     * @return string 微信返回的全部信息
     */
    public function getQrcodeUrl($scene_id, $action_name = 'QR_LIMIT_STR_SCENE')
    {

        $access_token = $this->getGeneralAccessToken();
        $data = [
            "action_name" => $action_name,
            "action_info" => [
                "scene" => [
                    "scene_str" => $scene_id,
                ],
            ],
        ];
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $access_token['accessToken'];

        $res = $this->postData($url, json_encode($data));

        $this->success('OK',json_decode($res, true)) ;
    }

    public function inviteshopQrcode($qr_code,$paytype,$order_sn)
    {

        $image=$order_sn.'_'.$paytype.'.png';
        $result = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            // ->data(Request::instance()->domain() . '/manystore?id=' . $uid)
            ->data($qr_code)
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(300)
            ->margin(10)
            ->build();

        $result->saveToFile(ROOT_PATH . 'public/uploads/qrcode/'.$image);
        $exist = file_exists(ROOT_PATH . 'public/uploads/qrcode/'.$image);
        if (!$exist) $this->error('获取二维码失败');


        return   cdnurl('/uploads/qrcode/'.$image,true);


    }



    public function bind_wechat()
    {
        $url = '/';

      //  $admin_id = $this->auth->id;
      //  $domain = $this->request->get('domain');

//        if (empty($admin_id) || empty($domain)) {
//            $this->error("参数错误", $url);
//        }

//        $open_id = Db::name('admin')
//            ->where('id', $admin_id)
//            ->where('status', 'normal')
//            ->value('open_id');

//        if (!empty($open_id)) {
//            $this->error("已绑定过微信");
//        }

//        $domain_id = \app\admin\model\Domain::where('domain',$domain)
//            ->where('status',1)
//            ->value('id');

//        if(!$domain_id) {
//            $this->error("场所不存在");
//        }

      //  $param = ['type' => 2, 'admin_id' => $admin_id, 'domain_id' => $domain_id];
        $param = ['type' => 2, 'admin_id' => 0, 'domain_id' => 0];
        $scene_id = json_encode($param);
        // dump($scene_id);


//        $wx = new WxFunction();
        $qrcodeRes = json_decode($this->getQrcodeUrl($scene_id, 'QR_STR_SCENE'), true);
       // dump($qrcodeRes);
        if (empty($qrcodeRes['errcode'])) {
            $ticket = $qrcodeRes['ticket'];
            // 通过ticket换取二维码
            $qrcode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . $ticket;
            $data['qrcode'] = $qrcode;
            $data['scene_id'] = $scene_id;

//            Db::table('tp_admin_wechat_login_log')
//                ->insert([
//                    'type' => 2,
//                    'ticket' => $ticket,
//                    'admin_id' => $admin_id,
//                    'domain_id' => $domain_id,
//                    'is_login' => 0,
//                    'create_time' => time()
//                ]);

        } else {
            Log::error($qrcodeRes['errcode'] . "错误信息" . $qrcodeRes['errmsg']);
            $this->error("获取二维码失败", $url);
        }

        $background = Config::get('fastadmin.login_background');
        $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
        $this->view->assign('background', $background);
        $this->view->assign('title', "绑定微信");

        $this->success('OK', $data);

       // return $this->view->fetch();
    }


    public function checkBind()
    {
        $url = '/';

        $scene_id = $this->request->post('scene_id');
        if (empty($scene_id)) {
            $this->error("参数错误", $url);
        }

        $scene_id = json_decode($scene_id, true);

        $admin_id = $scene_id['admin_id'];
        $domain_id = $scene_id['domain_id'];

        if (empty($admin_id) || empty($domain_id)) {
            $this->error("参数错误", $url);
        }

        $open_id = Db::name('admin')
            ->where('id', $admin_id)
            ->where('domain_id', $domain_id)
            ->where('status', 'normal')
            ->value('open_id');

        if (empty($open_id)) {
            $this->error("暂未绑定");
        }

        $this->success("绑定成功");
    }

    public function unbind_wechat()
    {
        $url = '/';

        $admin_id = $this->auth->id;

        if (empty($admin_id)) {
            $this->error("参数错误", $url);
        }

        Db::name('admin')
            ->where('id', $admin_id)
            ->where('status', 'normal')
            ->update(['open_id' => '']);

        $this->success("解绑成功");
    }

    public function verifyToken()
    {

        $data = $this->request->param();

        if (empty($data['signature']) || empty($data['timestamp']) || empty($data['nonce']) || empty($data['echostr'])) {
            return -1;
        }

        $signature = $data['signature'];
        $timestamp = $data['timestamp'];
        $nonce = $data['nonce'];
        $echostr = $data['echostr'];

        $token = '3984d5bde23df705ed0535b52dca93d3';

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return $echostr;
        } else {
            return -1;
        }
    }

}